package com.example.springboot_shiro.shiro.realm;

import com.example.springboot_shiro.entity.Pers;
import com.example.springboot_shiro.entity.Role;
import com.example.springboot_shiro.entity.User;
import com.example.springboot_shiro.service.UserService;
import com.example.springboot_shiro.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

//自定义realm
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
       UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
       User user = userService.findRolesByUserName(primaryPrincipal);
        //授权角色信息
        if(!CollectionUtils.isEmpty(user.getRoles())){
            final SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role->{
                simpleAuthorizationInfo.addRole(role.getName());

                //权限信息
                List<Pers> pers = userService.findPersByRoleId(role.getId());
                if(!CollectionUtils.isEmpty(pers)){
                    pers.forEach(pers1 ->{
                        simpleAuthorizationInfo.addStringPermission(pers1.getName());
                    } );
                }
            });
        return simpleAuthorizationInfo;
        }

        return null;

    }






    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("==========");
        String principal = (String) authenticationToken.getPrincipal();
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(),
                    user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }


        return null;
    }
}
